package com.raychi.demo.service;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import com.raychi.demo.dao.ProductDao;
import com.raychi.demo.entity.Product;
import com.raychi.demo.util.JdbcUtil;

public class ProductService {
	private ProductDao productDao;
	
	public List<Product> getProducts() throws ClassNotFoundException, SQLException{
		Connection conn = null;
		List<Product> list = null;
		try{
			conn = JdbcUtil.getConnection();
			list = productDao.getProducts(conn);
			conn.commit();
		}catch(Exception e){
			JdbcUtil.closeConnection(conn);
		}finally{
			JdbcUtil.rollback(conn);
		}
		return list;
	}
	
	public void delete(Product product){
		Connection conn = null;
		try{
			conn = JdbcUtil.getConnection();
			productDao.delete(product, conn);
			conn.commit();
		}catch(Exception e){
			JdbcUtil.rollback(conn);
		}finally{
			JdbcUtil.closeConnection(conn);
		}
	}
	
	public void update(Product product){
		Connection conn = null;
		try{
			conn = JdbcUtil.getConnection();
			productDao.update(product, conn);
			conn.commit();
		}catch(Exception e){
			JdbcUtil.rollback(conn);;
		}finally{
			JdbcUtil.closeConnection(conn);
		}
	}
	
	public void save(Product product){
		Connection conn = null;
		try{
			conn = JdbcUtil.getConnection();
			productDao.save(product, conn);
			conn.commit();
		}catch(Exception e){
			e.printStackTrace();
			JdbcUtil.rollback(conn);
		}finally{
			JdbcUtil.closeConnection(conn);
		}
	}
	

	public void setProductDao(ProductDao productDao) {
		this.productDao = productDao;
	}
}
